package com.mic.current;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

/**
 * Created by yjq14 on 2018/2/19.
 */
public class DeadLockChecker {
    private final static ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
    final static Runnable deadLockCheck = () -> {
        while (true) {
            long[] deadlockedThreadIds = mbean.findDeadlockedThreads();
            if (deadlockedThreadIds != null) {
                ThreadInfo[] threadInfos = mbean.getThreadInfo(deadlockedThreadIds);
                for (Thread t :
                        Thread.getAllStackTraces().keySet()) {
                    for (int i = 0; i < threadInfos.length; i++) {
                        if (t.getId() == threadInfos[i].getThreadId()) {
                            t.interrupt();
                        }
                    }
                }
            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    public static void check() {
        Thread thread = new Thread(deadLockCheck);
        thread.setDaemon(true);
        thread.start();
    }
}
